/**
 * Created by shenyinlin on 2018/6/24.
 */
import {DataStore} from "./base/DataStore.js";

import {UpPencil} from "./runtime/UpPencil.js";
import {DownPencil} from "./runtime/DownPencil.js";

import {Score} from "./player/Score.js";
import Request from './base/request.js';
import ServerUrl from './base/ServerUrl.js';
//导演类，控制游戏的逻辑
export class Director {


 
    constructor() {
        console.log('director constructor');
        this.dataStore = DataStore.getInstance();
        //地板及蜡烛的移动速度
        this.moveSpeed = 2;
    }


    createPencil() {
      const minTop = DataStore.getInstance().canvas.height / 8;
      const maxTop = DataStore.getInstance().canvas.height / 2;
        const top = minTop + Math.random() * (maxTop - minTop);

        this.dataStore.get('pencils').push(new UpPencil(top));
        this.dataStore.get('pencils').push(new DownPencil(top));
    }


    static  getInstance() {
        if (!Director.instance) {
            Director.instance = new Director();
        }
        return Director.instance;
    }

    //马被点击
    //循环给三只马更改坐标
    birdsEvent() {
        for (let i = 0; i <= 2; i++) {
            // console.log('before birds.y[i]' + this.dataStore.get('birds').y[i]);
            // console.log('birds.birdsY[i]' + this.dataStore.get('birds').birdsY[i]);
            //所谓的往上提 就是回到之前的y轴位置
            this.dataStore.get('birds').y[i] =
            this.dataStore.get('birds').birdsY[i];
            // console.log('after.y[i]' + this.dataStore.get('birds').y[i]);

        }

        //重置自由落体的时间，否则下落会越来越快
        this.dataStore.get('birds').time = 0;
    }


    //小马是否和蜡烛撞击
    static isStrike(bird, pencil) {
        let s = false;
        //case1:小马的顶部,撞到上半部分蜡烛的底部了(超越了)
        //case2:小马的底部碰到下面蜡烛的顶部啦
        //case3:小马的右边撞到了笔的左边
        //case4:小马的左边撞到了蜡烛的右边


        if (bird.top > pencil.bottom
            || bird.bottom < pencil.top
            || bird.right < pencil.left
            || bird.left > pencil.right
        ) {
            s = true;
            // console.log(bird.top + '|'+ pencil.bottom);
            // console.log(bird.bottom + '|'+ pencil.top);
            // console.log(bird.right + '|'+ pencil.left);
            // console.log(bird.left + '|'+ pencil.right);
        }


        //之所以取反值，是因为游戏初始化的时候不计问题.
        //初始化时候的值
        // 333.5|420
        // 357.5|0
        // 127.75|375 条件被满足
        // 93.75|427
        return !s;
    }


    //判断小马是否碰到地板或者蜡烛
    check() {

        const birds = this.dataStore.get('birds');

        const land = this.dataStore.get('land');

        //因为蜡烛是随机的,先拿出现在这一刻所有的蜡烛
        const pencils = this.dataStore.get('pencils');

        const score = this.dataStore.get('score');


        //地板的撞击判断 随便拿只马都有代表性.
        //如果马现在的y轴位置 + 马的身高 等于地板的y轴位置，说明它彻底降落了啊
        if (birds.birdsY[0] + birds.birdsHeight[0] >= land.y) {
          this.playBoomAudio();
            console.log('撞地板!');
            this.isGameOver = true;
            return;
        }

        //小马的边框模型 上下左右的目前位置。检测碰撞
        const birdsBorder = {
            //小马的y坐标
            top: birds.y[0],
            //小马的顶上的Y轴位置+小马的自身身高
            bottom: birds.birdsY[0] + birds.birdsHeight[0],
            //小马的x轴最左边的坐标点
            left: birds.birdsX[0],
            //小马的右边的坐标点，从左边加上自己的身胖
            right: birds.birdsX[0] + birds.birdsWidth[0]

        };


        const length = pencils.length;
        //循环给每个蜡烛单独建模
        for (let i = 0; i < length; i++) {
            const pencil = pencils[i];
            const pencilBorder = {
                top: pencil.y,
                bottom: pencil.y + pencil.height,
                left: pencil.x,
                right: pencil.x + pencil.width
            }
            //对比每一只蜡烛
            if (Director.isStrike(birdsBorder, pencilBorder)) {
                 this.playBoomAudio();
                console.log('撞到蜡烛了');
                this.isGameOver = true; 
                return;
            }
        }


        //加分逻辑 如果马的横坐标越过第一根笔的横坐标+笔的宽度,就算给他分
        if(birds.birdsX[0]>pencils[0].x+pencils[0].width && score.getIsScore()){
            score.addScore();
            score.updateIsScore();
        }

    }


    //播放撞墙音效
    playBoomAudio() {
      this.boom = wx.createInnerAudioContext();
      this.boom.src = './audio/boom.mp3'; // src 可以设置 http(s) 的路径，本地文件路径或者代码包文件路径
      //自动播放么?
      this.boom.autoplay = false;
      //无线循环么
      this.boom.loop = false;
      this.boom.play();

    } 




    //游戏未开始的准备页面,显示一些开始前的布局
    readyPage(isFirstPlay){


        this.dataStore.get('homeBackground').draw();
        //是不是第一次游戏呀,是否已经培训过?
        let isStudyOver= this.dataStore.get('isStudyOver');
        // console.log((isFirstPlay===''));
        // console.log((isStudyOver !=true));

       if(isFirstPlay==='' && isStudyOver !=true){
            // console.log('isFirstPlay='+ isFirstPlay);

            this.dataStore.get('firstStudy').draw();

            this.dataStore.put('isStudyOver',true);
           //设置为false
           wx.setStorageSync('isFirstPlay',false);
       }else{

           this.dataStore.get('paiHangBtn').draw();
       }


        this.dataStore.get('okButton').draw();

    }



    //游戏开始运行
    run() {




        //触碰检测
        this.check();



        //如果游戏没有结束
        if (!this.isGameOver) {
            this.dataStore.get('background').draw();

            const pencils = this.dataStore.get('pencils');

            //如果蜡烛的坐标加上宽度 <=0，在屏幕左侧即将被淹没 ，并且数组中目前有四根
            if (pencils[0].x + pencils[0].width <= 0 && pencils.length == 4) {
                pencils.shift();
                pencils.shift();
                //蜡烛回收了，加分flag回归正常
                this.dataStore.get('score').updateIsScore();
            }

            if (pencils[0].x <= (DataStore.getInstance().canvas.width - pencils[0].width) / 2
                && pencils.length === 2) {
                //再次创建两根蜡烛
                this.createPencil();
            }


            this.dataStore.get('pencils').forEach(function (value) {
                value.draw();
            });

            this.dataStore.get('land').draw();

            this.dataStore.get('score').draw();

            this.dataStore.get('birds').draw();

            let timer = requestAnimationFrame(() => this.run());

            this.dataStore.put('timer', timer);
        } else {
            //音乐停掉啊
            this.stopAudio();

            console.log('GAME OVER'); 
//            this.dataStore.get('startButton').draw();


            //最终分数
            let overScore = this.dataStore.get('score').getNowScore();

            let openid = wx.getStorageSync('openid');

            const data = {
                score:overScore,
                openid:openid
            }
            const url = ServerUrl.platformManager + 'updateScore'
            //更新分数
            Request.postRequest(url, data).then(function (result) {
                console.log('result:'+JSON.stringify(result));

                // wx.setStorageSync('openid',openid);
            })

            //展示分数面板
            this.dataStore.get('scoreItem').draw();

            //正在看分数面板 这个条件不存在 TODO FIX ME
            this.dataStore.put('scoreItemShow',true);

            // this.dataStore.get('back').draw();

            //展示分数
            this.dataStore.get('score').drawGameOver();

            //展示评级
            this.dataStore.get('score').drawGameOverFont();


            //游戏没有正在进行
            this.dataStore.put('gameIsStart',false);

            //游戏已经终止,取消动画刷新
            cancelAnimationFrame(this.dataStore.get('timer'));
            //释放数据缓存
            // this.dataStore.destory();
            //Gc回收
            wx.triggerGC();
            
        }


    }


    //播放音乐 BGM
    playAudio(){
        this.bgm = wx.createInnerAudioContext();
        this.bgm.src = './audio/bgm.mp3'; // src 可以设置 http(s) 的路径，本地文件路径或者代码包文件路径
        //自动播放么?
        this.bgm.autoplay = true;
        //无线循环么
        this.bgm.loop = false;
        this.bgm.play();

    }
    //停掉音乐
    stopAudio(){
        this.bgm.stop();
    }
}